<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class GoodsRecord extends Model
{
    // 表名
    protected $name = 'goods_record';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
        'end_time_text',
        'open_time_text',
	    'status_text',
	    'is_robot_text'
    ];
	
	const STATUS_F = 2;
	const STATUS_W = 1;
	const STATUS_B = 0;
	
	
	public static $statusList = [
		self::STATUS_F => '已开奖',
		self::STATUS_W => '开奖中',
		self::STATUS_B => '进行中'
	];
 
	public function getStatusTextAttr($value, $data) {
		$value = $value ? $value : $data['status'];
		$list = self::$statusList;
		return isset($list[$value]) ? $list[$value] : '';
	}

	
	const ROBOT_Y = 1;
	const ROBOT_N = 0;
	
	public static $robotList = [
		self::ROBOT_Y => '是',
		self::ROBOT_N => '否'
	];
	
	public function getIsRobotTextAttr($value, $data) {
		$value = $value ? $value : $data['is_robot'];
		$list = self::$robotList;
		return isset($list[$value]) ? $list[$value] : '';
	}
	

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOpenTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['open_time']) ? $data['open_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setEndTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setOpenTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
    public function goods(){
    	return $this->belongsTo('Goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
    }
	
	/**
	 * 获取数据
	 * @param $page
	 * @param $order
	 * @return false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getRows($page, $order) {
		$rows = Db::name('goodsRecord')->alias('r')
			->join('goods g', 'r.goods_id = g.id', 'left')
			->where([
				'g.is_sale' => \app\common\model\Goods::SALE_Y,
				'r.status' => self::STATUS_B,
			])
			->field('r.id, g.goods_name, g.image, r.total_number, r.buy_number')
			->order($order)
			->page($page)
			->select();
		
		return $rows;
	}
	
	/**
	 * 创建商品基数
	 * @param $goodsId 商品ID
	 * @param $number 购买数量
	 * @return false|int
	 */
	public function createRecord($goodsId, $number){
		$oneAmount = \think\Config::get('oneAmount');
		$data = [
			'goods_id' => $goodsId,
			'total_number' => ceil($number/$oneAmount)
		];
		return $this->isUpdate(false)->save($data);
	}
	
	
	/**
	 * 创建机器人订单
	 * @param $row
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
	public function createRobot($row) {
		//判断以前是否有指定，有就直接更改状态，没有生成机器人订单，再更改指定状态和开奖ID
		$this->startTrans();
		try {
			if($row['buy_id']) {
				$res = $this->save(['is_robot' => self::ROBOT_Y], ['id' => $row['id']]);
			} else {
				$model = new BuyRecord();
				$buyId = $model->createRobotOrder($row);
				if(!$buyId){
					throw new Exception('创建机器人订单出错');
				}
				
				$res = $this->save(['is_robot' => self::ROBOT_Y, 'buy_id' => $buyId], ['id' => $row['id']]);
			}
			
			if(!$res) {
				throw new Exception('更改开奖状态出错');
			}
			
			$this->commit();
			return true;
			
		} catch(Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	
	
}
